package wetalk.software.bupt.com.wetalk.view.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jyt.message.Message;
import com.jyt.util.MySerializable;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import wetalk.software.bupt.com.wetalk.GloableParams;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.listener.PushListener;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.util.SharePreferenceUtil;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.view.dialog.CustomDialog;
import wetalk.software.bupt.com.wetalk.widget.ClearEditText;

import static android.content.ContentValues.TAG;
import static wetalk.software.bupt.com.wetalk.application.MyApplication.getContext;

public class UpdatePhoneNumberActivity extends BaseActivity {
    private IntentFilter intentFilter;
    private PhoneUserInfoReceiver userInfoReceiver;
    private TextView mPhoneNumber;
    private RelativeLayout rvImgBack;
    private RelativeLayout rvImgUpdatePhone;
    private Intent intent;
    private ClearEditText mNewPhone;//显示手机号
    private AndroidClientService.SendBinder sendBinder;
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_phone_number);
        initWidget();
        initModifyUserInfoBC();
        initEvent();

    }


    /*初始化控件*/
    private void initWidget() {
        rvImgBack=(RelativeLayout)findViewById(R.id.rv_img_back);
        rvImgUpdatePhone=(RelativeLayout)findViewById(R.id.rv_img_right);
        mNewPhone=(ClearEditText) findViewById(R.id.et_update_phonenumber);
        mPhoneNumber = (TextView) findViewById(R.id.tv_original_phonenumber);

        //客户端发送消息
        Intent bindIntent = new Intent(this, AndroidClientService.class);
        this.bindService(bindIntent, connection, BIND_AUTO_CREATE);

        //中间文字“修改手机号”
        TextView txtMiddle=(TextView)findViewById(R.id.txt_title);
        txtMiddle.setText("更改手机号");

        //接收个人信息页面传来的原手机号
        intent = getIntent();
        String data = intent.getStringExtra("extra_phone");
        mPhoneNumber.setText("原手机号："+data);
    }

    private void initEvent(){

        //点击左侧布局事件
        rvImgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //修改确定按钮
        rvImgUpdatePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phoneNumber=mNewPhone.getText().toString();
                if(phoneNumber.equals(""))
                {
                    Toast.makeText(UpdatePhoneNumberActivity.this,"请正确输入手机号，不可为空",Toast.LENGTH_SHORT).show();
                }
                else if (isMobileNO(phoneNumber)==false)
                {
                    Toast.makeText(UpdatePhoneNumberActivity.this,"请正确输入十一位手机号",Toast.LENGTH_SHORT).show();
                }
                else {
                    sendModifyUserInfo(phoneNumber, new PushListener() {
                        @Override
                        public void onSuccess() {
                            Toast.makeText(UpdatePhoneNumberActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(int var1, String var2) {
                            Toast.makeText(UpdatePhoneNumberActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                    CustomDialog.getDialog(UpdatePhoneNumberActivity.this,"正在修改...").show();
                }

            }
        });
    }

    public static boolean isMobileNO(String mobiles){
        Pattern p = Pattern.compile("^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }


    //发送修改消息
    private void sendModifyUserInfo(String context, final PushListener pushCallback)  {

        User saveUser = UserManager.getInstance(this).getCurrentUser();
        final String targetId = "sys_userinfo";
        final String userId= saveUser.getUserID();
        final JSONObject json=new JSONObject();


        //读取原始密码
        SharePreferenceUtil sharePreferenceUtil = new SharePreferenceUtil(getContext(), "WeTalk_SP");
        String originalPs = sharePreferenceUtil.getValue("password");

        try {
            json.put("id",userId);
            json.put("phone",context);
            json.put("email",saveUser.getEmail());
            json.put("passwd",originalPs);


        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"modifyUserInfo",bs);
                sendBinder.sendMessage(msg);
                Log.i(TAG, "send message: "+msg);
                //pushCallback.onSuccess();
            }
        });
        thread.start();

    }

    //注册广播接收器
    private void initModifyUserInfoBC(){
        //接收广播
        intentFilter=new IntentFilter(WeTalkConfig.BROADCAST_MODIFY_USER_INFO);
        userInfoReceiver=new PhoneUserInfoReceiver();
        registerReceiver(userInfoReceiver,intentFilter);
    }
   //广播接收器
    class PhoneUserInfoReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            CustomDialog.getDialog(UpdatePhoneNumberActivity.this,"正在修改...").close();
            String result=null;
            String content=intent.getStringExtra("result");
            try {
                JSONObject json=new JSONObject(content);
                result=json.getString("result");
                if(result.equals("success")){
                    Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();
                    SharePreferenceUtil sharePreferenceUtil = new SharePreferenceUtil(context, "WeTalk_SP");
                    User user = (User)sharePreferenceUtil.readObject("user");
                    user.setPhone(mNewPhone.getText().toString());
                    sharePreferenceUtil.saveObject(user,"user");
                    GloableParams.PHONE = mNewPhone.getText().toString();
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(userInfoReceiver);
        unbindService(connection);
    }

}
